package com.cyzy.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cyzy.dto.Result;

import com.cyzy.pojo.Contract;
import com.cyzy.pojo.Course;
import com.cyzy.pojo.Seckill;
import com.cyzy.pojo.SeckillJoin;
import com.cyzy.service.CampusService;
import com.cyzy.utils.AliyunOcrUtil;
import com.cyzy.utils.ElectronicContractsUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.List;
import java.util.Map;

/**
 * 校区负责人
 */
@RequestMapping("/leader")
@RestController
public class LeaderController {

    @Value("${file.imgFile}")
    private String path;

    @Value("${file.idImgFile}")
    private String idImgFilePath;


    @Autowired
    private AliyunOcrUtil aliyunOcrUtil;

    @Autowired
    private CampusService campusService;

    @Autowired
    private ElectronicContractsUtil electronicContractsUtil;
    /**
     * 识别营业执照，并返回信息
     */
    @PostMapping("/LicenseRecognition")
    public Result LicenseRecognition(@RequestParam("file") MultipartFile imgFile) throws Exception {
        if (imgFile.isEmpty()){
            return Result.ok().message("上传的文件为空！");
        }

        //保存的路径位置
        String filePath=path+"\\"+imgFile.getOriginalFilename();

        //将上传的目录保存导目录下
        imgFile.transferTo(new File(filePath));
        //调用阿里云OCR
        Map<String,Object> result=aliyunOcrUtil.method(filePath);

        if (result==null){
            return Result.ok().message("识别失败");
        }
        result.put("filePath",filePath);
        return Result.ok().data("info",result);
    }

    /**
     * 生成电子合同模板
     */
    @GetMapping("/CreateContract")
    public Result CreateContract(){

        String contractPath = electronicContractsUtil.createContract();
        return Result.ok().message("创建电子合同").data("contractPath",contractPath);
    }

    /**
     * 身份证识别
     */
    @PostMapping("/idNumberRecognition")
    public Result idNumberRecognition(@RequestParam("file") MultipartFile imgFile) throws Exception {
        if (imgFile.isEmpty()){
            return Result.ok().message("上传的文件为空！");
        }

        //保存的路径位置
        String filePath=idImgFilePath+"\\"+imgFile.getOriginalFilename();

        //将上传的目录保存导目录下
        imgFile.transferTo(new File(filePath));
        //调用阿里云OCR
        Map<String,Object> result=aliyunOcrUtil.idNumber(filePath);
        System.out.println(result);
        if (result==null){
            return Result.ok().message("识别失败");
        }
        result.put("filePath",filePath);
        return Result.ok().data("info",result);
    }

    /**
     * 入驻申请
     * 接受营业执照，身份证（人像面）
     * 还有入驻信息
     */
    @PostMapping("/applyEntry")
    public Result applyForEntry(
            @RequestParam("license") MultipartFile licenseFile,  // 营业执照文件
            @RequestParam("idCard") MultipartFile idCardFile,    // 身份证文件
            @RequestParam("contractAmount") Double contractAmount,
            @RequestParam("campusName") String campusName,
            @RequestParam("startDate") String startDate,
            @RequestParam("endDate") String endDate,
            @RequestParam("phone") String phone,
            @RequestParam("email") String email
    ) {
        try {
            // 1. 校验文件是否为空
            if (licenseFile.isEmpty()) {
                return Result.error().message("请上传营业执照");
            }
            if (idCardFile.isEmpty()) {
                return Result.error().message("请上传身份证人像面照片");
            }

            // 2. 处理文件
            String licenseFileName = licenseFile.getOriginalFilename();
            String idCardFileName = idCardFile.getOriginalFilename();

            // 3. 保存文件到服务器或云存储
             saveFile(licenseFile, "license/");
             saveFile(idCardFile, "idCard/");

            // 4. 处理其他业务参数（如保存到数据库）
            System.out.println("校区名称：" + campusName);
            System.out.println("合同金额：" + contractAmount);
            System.out.println("开始时间：" + startDate);
            System.out.println("结束时间：" + endDate);
            System.out.println("电话：" + phone);
            System.out.println("邮箱：" + email);

            return Result.ok().message("申请入驻成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error().message("申请入驻失败：" + e.getMessage());
        }
    }


    private void saveFile(MultipartFile file, String directory) throws Exception {
        // 文件保存到服务器本地路径
        String filePath = "C:\\Users\\yangjingshi\\Desktop\\四阶项目\\" + directory + file.getOriginalFilename();
        System.out.println(filePath);
        file.transferTo(new File(filePath));
    }

    /**
     * @description: fen
     * @author: yangJingShi
     * @date: 2025/5/22 下午4:16
     * @param: [pageSize, currentPage, userId, contractAmount, paymentStatus, startDate, endDate, signTime]
     * @return: com.cyzy.dto.Result
     **/
    @GetMapping("/paginationContract")
    public Result paginationContract(@RequestParam("pageSize") Long pageSize,
                                     @RequestParam("currentPage") Long currentPage,
                                     @RequestParam("userId") Long userId,
                                     //条件查询
                                     @RequestParam("contractAmount")Double contractAmount,
                                     @RequestParam("paymentStatus") String paymentStatus,
                                     @RequestParam("startDate") String startDate,
                                     @RequestParam("endDate") String endDate,
                                     @RequestParam("signTime") String signTime){
        System.out.println(signTime);
        Page<Contract> contractPage = campusService.selectContractByUserId(userId, pageSize, currentPage,contractAmount,paymentStatus,startDate,endDate,signTime);
        System.out.println(contractPage);
        return Result.ok().data("contracts",contractPage);
    }

    /**
     * @description: 查看负责人申请秒杀活动的记录
     * @author: yangJingShi
     * @date: 2025/5/22 上午11:01
     * @param: [pageSize, currentPage, userId]
     * @return: com.cyzy.dto.Result
     **/
    @GetMapping("/getAllSecKill")
    public Result getAllSecKill(@RequestParam("pageSize") Long pageSize,
                                @RequestParam("currentPage") Long currentPage,
                                @RequestParam("userId") Long userId
                                ){
        System.out.println(pageSize);
        System.out.println(currentPage);
        System.out.println(userId);
        Page<SeckillJoin> allSecKill = campusService.getAllSecKill(userId, pageSize, currentPage);
        return Result.ok().data("allSecKill",allSecKill);
    }

    /**
     * @description: 新增秒杀申请记录
     * @author: yangJingShi
     * @date: 2025/5/22 下午3:04
     * @param: [seckill]
     * @return: com.cyzy.dto.Result
     **/
    @PostMapping("/insertSecKill")
    public Result insertSecKill(@RequestBody Seckill seckill){
        int i = campusService.insertSecKill(seckill);
        return Result.ok().message("新增一个秒杀活动申请");
    }

    /**
     * @description: 申请秒杀活动表单时通过campusId查询校区名称
     * @author: yangJingShi
     * @date: 2025/5/22 下午4:25
     * @param: [userId]
     * @return: com.cyzy.dto.Result
     **/
    @GetMapping("/queryCampusNameWhenSecKill")
    public Result queryCampusNameWhenSecKill(@RequestParam("campusId") Long campusId){
        String campusName = campusService.queryCampusNameWhenSecKill(campusId);
        return Result.ok().data("campusName",campusName);
    }

    /**
     * @description: 获取校区对应的所有课程
     * type:0是正常、1是禁用、2是审核
     * @author: yangJingShi
     * @date: 2025/5/22 下午5:06
     * @param: [campusId]
     * @return: com.cyzy.dto.Result
     **/
    @GetMapping("/queryAllCourseByCampusId")
    public Result queryAllCourseByCampusId(@RequestParam("campusId") Long campusId){
        List<Course> courseList = campusService.queryAllCourseByCampusId(campusId, 1);
        return Result.ok().data("courseList",courseList);
    }


}
